package javabase.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <pre>
 *   Title: MySingleton.java
 *   Description: 
 *   Copyright: yundaex.com Copyright (c) 2013
 *   Company: 上海韵达货运有限公司
 * </pre>
 * 
 * @author liuzhaoqing
 * @version 1.0
 * @date 2014年11月3日
 */
public class MySafetySingleton {

	private static MySafetySingleton mySingleton;
	/*
	 * 原子计数器
	 */
	private static AtomicInteger count = new AtomicInteger(0);
	
	/*
	 *锁 
	 */
	private static ReentrantLock lock = new ReentrantLock();
	
	/*
	 * 私有化构造方法,模拟长时间初始化
	 */
	private MySafetySingleton() {
		try {
			Thread.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(count.incrementAndGet());
	}
	
	private static MySafetySingleton getInstance() {
		if (mySingleton == null) {
			try {
				lock.lock();
				if (mySingleton == null) {
					mySingleton = new MySafetySingleton();
				}
			} finally {
				lock.unlock();
			}
		}
		return mySingleton;
	}
	
	public static class TestRun implements Runnable {
		public void run() {
			System.out.println(MySafetySingleton.getInstance());
		}
	}
	
	public static void main(String[] args) {
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 0; i<20; i++) {
			executorService.execute(new TestRun());
		}
		executorService.shutdown();
		try {
			executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
